package Java7_Concurrency_Cookbook.thread_executor_framework.scheduled_thread_pool_executor;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 如果不想任务马上执行, 而想让任务在过一段时间之后才被执行, 或者周期性的执行.<br/>
 * 为了达到这个目的, 执行框架提供了ScheduledThreadPoolExecutor类<br/>
 *
 * executor.shutdown()方法执行后, 待处理的任务仍会被执行<br/>
 * 通过executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false)设置,<br/>
 * 待处理的任务将不会被执行
 * @author lixiangke
 * @date 2017/11/18
 */
public class Main {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor)
                Executors.newScheduledThreadPool(1);
        System.out.printf("Main: Starting at: %s \n", new Date());
        for (int i = 0; i < 5; i++) {
            Task tasks = new Task("Zoom" + i);
            executor.schedule(tasks, i * 2, TimeUnit.SECONDS);
        }
        executor.shutdown();
        System.out.println("executor.shutdown()");
        try {
            executor.awaitTermination(1, TimeUnit.DAYS);
            System.out.println("awaitTermination");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Main: Ends at: %s\n", new Date());
    }
}
